import { ref, customRef } from 'vue'

// 节流函数
export function useThrottleFn(fn: Function, delay: number) {
  let timeout: NodeJS.Timeout | null = null
  let lastRun = 0

  return function (...args: any[]) {
    const now = Date.now()

    if (lastRun && now < lastRun + delay) {
      if (timeout) {
        clearTimeout(timeout)
      }
      timeout = setTimeout(() => {
        lastRun = now
        fn.apply(this, args)
      }, delay)
    } else {
      lastRun = now
      fn.apply(this, args)
    }
  }
}

// 防抖函数
export function useDebounceFn(fn: Function, delay: number) {
  let timeout: NodeJS.Timeout | null = null

  return function (...args: any[]) {
    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}